import datetime

import pandas as pd

import Global


class Stock:
    code = ""
    nowPrice = 0.0

    oldMinData = pd.DataFrame({})
    oldDayData = pd.DataFrame({})
    nowDayData = pd.DataFrame({})
    nowMinData = pd.DataFrame({})

    futureMinData = pd.DataFrame({})
    futureDayData = pd.DataFrame({})

    def __init__(self, code):
        self.code = code
        self.getAllData()  # 获取旧信息
        Global.stockList.append(self)

    def getAllData(self):
        end = datetime.datetime.strptime(Global.startDate, "%Y-%m-%d") - datetime.timedelta(days=1)  # 获取到开始前一天
        start = end - datetime.timedelta(days=200)  # 设置结束在开始前200天的日期
        self.oldDayData = Global.getDayData(self.code, start, end)  # 获取历史股价
        self.nowPrice = float(self.oldDayData.open_price.values[-1])  # 设置最新价格

        self.futureDayData = Global.getDayData(self.code, Global.startDate, Global.endDate)  # 获取未来数据

    def nextDay(self):  # 下一日
        if len(Global.stockList) == 0:
            return
        if len(self.futureDayData) == 0:
            return
        for user in Global.userList:
            user.startEntrust()  # 执行委托

        self.oldDayData = pd.concat([self.oldDayData, self.futureDayData[0:1]], ignore_index=True)  # 将未来数据第一行添加到历史数据
        self.futureDayData = self.futureDayData[1:]  # 未来数据往后移
        self.nowDayData = self.oldDayData[-1:]
        self.nowPrice = float(self.oldDayData.open_price.values[-1])  # 设置最新价格

        self.futureMinData = Global.getMinDate(self.code, self.oldDayData.trading_date.values[-1])  # 更新完日后 获取当日分钟数据

        for user in Global.userList:
            user.startEntrust()

        return True

    def nextMin(self):

        if len(Global.stockList) == 0:
            return False
        if len(self.futureMinData) == 0:
            return False

        for user in Global.userList:
            user.startEntrust()  # 执行委托

        self.oldMinData = pd.concat([self.oldMinData, self.futureMinData[0:1]], ignore_index=True)
        self.futureMinData = self.futureMinData[1:]
        self.nowMinData = self.oldMinData[-1:]
        self.nowPrice = float(self.oldMinData.open.values[-1])

        for user in Global.userList:
            user.startEntrust()
        return True

    def getTodayData(self):
        return self.oldDayData[-1]

    def getNowMin(self):
        return len(self.oldMinData)
